package com.example.applications

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class City : AppCompatActivity() {

    // 1. 定义城市列表
    private val cityList = listOf<String>("北京", "上海", "广州", "深圳", "杭州", "南京", "西安")

    // 2. 定义变量接收下拉列表
    private var spDropdown: Spinner? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_city)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 1. 获取下拉组件
        spDropdown = findViewById(R.id.spinner)
        // 2. 声明一个数组适配器
        var adapter = ArrayAdapter(this, R.layout.item_select, cityList)
        // 3. 把适配器设置给下拉列表
        spDropdown?.adapter = adapter
        // 4. 设置下拉框默认选中第一项
        spDropdown?.setSelection(0)

        // 如果设置的模式为dialog
        spDropdown?.prompt = "请选择城市"

        // 5. 监听选择了哪一项
        spDropdown?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                Toast.makeText(
                    this@City,
                    "你选择了" + cityList[position],
                    Toast.LENGTH_SHORT
                ).show()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("Not yet implemented")
            }
        }

    }
}